package com.keyinong.caizhengting.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.ImageUtilsTouxiang;
import com.keyinong.caizhengting.tools.ImgChangeUtil;
import com.keyinong.caizhengting.tools.MyShowDialog;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.tools.SystemBarTintManager;
import com.keyinong.caizhengting.activity.AdviseActivity;
import com.keyinong.caizhengting.activity.BookingNoticeActivity;
import com.keyinong.caizhengting.activity.CommentActivity;
import com.keyinong.caizhengting.activity.HolidayActivity;
import com.keyinong.caizhengting.activity.MyinfoActivity;
import com.keyinong.caizhengting.activity.MysetActivity;
import com.keyinong.caizhengting.activity.NewmessageActivity;
import com.keyinong.caizhengting.activity.QianbaoActivity;
import com.keyinong.caizhengting.activity.XiaotieshiActivity;
import com.keyinong.caizhengting.activity.XinshoujiaochengActivity;
import com.keyinong.caizhengting.entity.PersonalEntity;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.util.Auth;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;

/**
 * 个人中心
 */

public class MyFragment extends Fragment {

    private static final String IMG_HEAD_URI = "file:///sdcard/parkinapp/head.jpg";
    View iscatview = null;
    /**
     * 钱包
     */
    Button btn_qianbao;
    /**
     * 订餐日期
     */
    Button btn_riqi;
    /**
     * 节假日订餐
     */
    Button btn_jiejiari;
    /**
     * 营养分析
     */
    Button btn_yiyangfenxi;
    /**
     * 我的信息
     */
    Button btn_xinxi;
    /**
     * 反馈信息
     */
    Button btn_fankui;
    /**
     * 新手教程
     */
    Button btn_xinshoujiaocheng;
    /**
     * 员工评价
     */
    Button btn_update;
    /**
     * 设置
     */
    Button btn_tuichu;
    /**
     * 获得数据
     */
    ArrayList<PersonalEntity> infolist;
    HttpTools httptools = null;
    Dialog diaphoto;
    /**
     * 选择相册
     */
    TextView tv_album;
    /**
     * 照相
     */
    TextView tv_photograph;
    /**
     * 取消
     */
    TextView tv_cancal;
    SharedPreferences sp;
    Uri imgUri;
    /**
     * 姓名
     */
    private TextView tv_name;
    /**
     * 手机号
     */
    private TextView tv_shoujihao;
    /**
     * 余额
     */
    private TextView tv_yue;
    /**
     * 积分
     */
    private TextView tv_jifen;
    /**
     * 头像
     */
    private ImageView iv_touxiang;
    private RelativeLayout rl_touxiang;
    /**
     * 通知
     */
    private ImageView iv_tongzhi;
    private File zhstapp;
    private String key;
    private UploadManager uploadManager;
    private String toke;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getActivity().getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            //			getActivity().getWindow().addFlags(
            //					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        return inflater.inflate(R.layout.fragment_my, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        SystemBarTintManager tintManager = new SystemBarTintManager(
                getActivity());
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintColor(getResources().getColor(
                R.color.white_1));
        super.onActivityCreated(savedInstanceState);

        // 创建缓存目录，系统一运行就得创建缓存目录的，
        zhstapp = new File(Environment.getExternalStorageDirectory(),
                "zhstapp");
        if (!zhstapp.exists()) {
            zhstapp.mkdirs();
        }
        iv_touxiang = (ImageView) getView().findViewById(R.id.iv_touxiang);
        rl_touxiang = (RelativeLayout) getView().findViewById(R.id.rl_touxiang);
        tv_name = (TextView) getView().findViewById(R.id.tv_name);
        tv_shoujihao = (TextView) getView().findViewById(R.id.tv_shoujihao);
        tv_yue = (TextView) getView().findViewById(R.id.tv_yue);
        tv_jifen = (TextView) getView().findViewById(R.id.tv_jifen);
        iv_tongzhi = (ImageView) getView().findViewById(R.id.iv_tongzhi);
        //		ImageUtils.displayImage(getActivity(), sp.getString("avatar", ""),
        //				iv_touxiang, R.drawable.touxiang1);
        Personal();
        //头像
        rl_touxiang.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog();
            }
        });
        //通知
        iv_tongzhi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), NewmessageActivity.class);
                startActivity(intent);
            }
        });
        sp = getActivity().getSharedPreferences("spuser", Context.MODE_PRIVATE);
        ImageUtilsTouxiang.displayImage(getActivity(), sp.getString("avatar", ""),
                iv_touxiang, R.drawable.touxiang1);
        //钱包
        btn_qianbao = (Button) getView().findViewById(R.id.btn_qianbao);
        btn_qianbao.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getActivity().startActivity(new Intent(getActivity(), QianbaoActivity.class));
            }
        });
        //订餐日期
        btn_riqi = (Button) getView().findViewById(R.id.btn_riqi);
        btn_riqi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), BookingNoticeActivity.class);
                startActivity(intent);
            }
        });
        //节假日订餐
        btn_jiejiari = (Button) getView().findViewById(R.id.btn_jiejiari);
        btn_jiejiari.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), HolidayActivity.class);
                startActivity(intent);
//				Toast.makeText(getActivity(), "敬请期待...", Toast.LENGTH_SHORT).show();
            }
        });
        //*营养贴士
        btn_yiyangfenxi = (Button) getView().findViewById(R.id.btn_yiyangfenxi);
        btn_yiyangfenxi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), XiaotieshiActivity.class);
                startActivity(intent);
                //				Toast.makeText(getActivity(), "敬请期待...", Toast.LENGTH_SHORT).show();
            }
        });
        //我的信息
        btn_xinxi = (Button) getView().findViewById(R.id.btn_xinxi);
        btn_xinxi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), MyinfoActivity.class);
                startActivity(intent);
            }
        });
        //反馈信息
        btn_fankui = (Button) getView().findViewById(R.id.btn_fankui);
        btn_fankui.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), AdviseActivity.class);
                getActivity().startActivity(intent);
            }
        });
        //新手教程
        btn_xinshoujiaocheng = (Button) getView().findViewById(R.id.btn_xinshoujiaocheng);
        btn_xinshoujiaocheng.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), XinshoujiaochengActivity.class);
                getActivity().startActivity(intent);
                //				Toast.makeText(getActivity(), "敬请期待...", Toast.LENGTH_SHORT).show();
            }
        });
        //员工评价
        btn_update = (Button) getView().findViewById(R.id.btn_update);
        btn_update.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), CommentActivity.class);
                getActivity().startActivity(intent);
            }
        });
        //退出登录
        btn_tuichu = (Button) getView().findViewById(R.id.btn_tuichu);
        btn_tuichu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), MysetActivity.class);
                startActivity(intent);
//				tuichudialog();
            }
        });
        //获取七牛token
        toke = getUpToken0();

    }

    /**
     * 获取个人信息
     */
    private void Personal() {
        if (NetWorkUtil.isNetwork(getActivity()) == false) {
            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        infolist = new ArrayList<PersonalEntity>();
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        Log.i("zq", "token---" + token);
        if (httptools == null) {
            httptools = new HttpTools(getActivity());
        }
        httptools.person(token, new JsonPerson());
    }

    /**
     * 头像上传底部弹出菜单
     */
    private void dialog() {
        diaphoto = new Dialog(getActivity());
        diaphoto.requestWindowFeature(getActivity().getWindow().FEATURE_NO_TITLE);
        View photoview = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_photo, null);
        tv_album = (TextView) photoview.findViewById(R.id.tv_album);
        tv_photograph = (TextView) photoview.findViewById(R.id.tv_photograph);
        tv_cancal = (TextView) photoview.findViewById(R.id.tv_cancalPhoto);
        diaphoto.setContentView(photoview);

        diaphoto.setCancelable(false);
        diaphoto.setCanceledOnTouchOutside(false);
        WindowManager m = getActivity().getWindowManager();
        Display dp = m.getDefaultDisplay();
        Window diaWindow = diaphoto.getWindow();
        WindowManager.LayoutParams lp = diaWindow.getAttributes();
        diaWindow.setGravity(Gravity.BOTTOM);
        lp.width = dp.getWidth();
        diaWindow.setAttributes(lp);
        diaphoto.show();

        //拍照
        tv_album.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intentPICK = new Intent(Intent.ACTION_PICK, null);
                intentPICK
                        .setDataAndType(
                                MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                                "image/*");
                // 返回本界面触发
                startActivityForResult(intentPICK, 1);
                diaphoto.dismiss();
            }
        });
        //从相册中选择
        tv_photograph.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT,
                // Uri.parse(IMG_HEAD_URI));
                intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.parse(IMG_HEAD_URI));
                startActivityForResult(intentPhoto, 2);
                diaphoto.dismiss();
            }
        });
        //取消
        tv_cancal.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                diaphoto.dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {
            Uri uri = ImgChangeUtil.geturi(getActivity(), data);
            startPhotoZoom(uri);
        } else if (requestCode == 3 && data != null
                && resultCode == getActivity().RESULT_OK) {
            Bundle bundle = data.getExtras();
            // Log.e("lh", "bundle---" + bundle.toString());
            Bitmap bitmap = bundle.getParcelable("data");
            imgUri = ImgChangeUtil.saveBitmap(bitmap);
            // img_head.setImageBitmap(bitmap);
            String imguri = imgUri.getPath();
            getBitmab();
            //			uploadHead(imguri);
        } else if (requestCode == 2 && resultCode == getActivity().RESULT_OK
            /* && data != null */) {
            Uri uri = Uri.parse(IMG_HEAD_URI);
            startPhotoZoom(uri);
        }
    }

    /**
     * 裁剪我们从相册中拿到的图片 ；
     *
     * @param uri
     */
    private void startPhotoZoom(Uri uri) {
        // 跳转到裁剪界面 action = "com.android.camera.action.CROP" ；
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        //
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 获取七牛token
     */
    public String getUpToken0() {
        String AccessKey = "if9TbJKjKfmJfcfqsy6MmhuDDLetDmwgcAHcj3Ib";
        String SecretKey = "YOESNYsRTVxf8Hp0UTOVPzfk1WvMg6UWXiQ1agiB";
        Auth auth = Auth.create(AccessKey, SecretKey);
        return auth.uploadToken("zhengfu");
    }

    /**
     * 上传头像至七牛云
     */
    public void getBitmab() {

        //		bmp = BitmapFactory.decodeResource(getResources(), R.drawable.m_two);

        uploadManager = new UploadManager();

        key = generateRandomFilename();
        String token = toke;
        String imgpath = imgUri.getPath();
        uploadManager.put(imgpath, key, token, new UpCompletionHandler() {

            @SuppressLint("ShowToast")
            @Override
            public void complete(String key, ResponseInfo responseInfo, JSONObject jsonObject) {
                Log.i("zq", responseInfo.toString());
                if (responseInfo.statusCode == 200) {
                    //					Toast.makeText(getActivity(), "完成上传", 0).show();
                    updateLogo();
                } else {
                    Toast.makeText(getActivity(), "上传失败", 0).show();
                }
                Log.i("qiniu", key + ",\r\n " + responseInfo + ",\r\n " + jsonObject);
            }
        }, null);

    }

    /**
     * 上传头像名随机编号
     */
    public String generateRandomFilename() {
        String RandomFilename = "";
        Random rand = new Random();//生成随机数
        int random = rand.nextInt();

        Calendar calCurrent = Calendar.getInstance();
        int intDay = calCurrent.get(Calendar.DATE);
        int intMonth = calCurrent.get(Calendar.MONTH) + 1;
        int intYear = calCurrent.get(Calendar.YEAR);
        String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
                String.valueOf(intDay) + "_";


        RandomFilename = now + String.valueOf(random > 0 ? random : (-1) * random) + ".png";
        Log.i("zq", "date---" + RandomFilename);
        return RandomFilename;
    }

    /**
     * 更新头像
     */
    private void updateLogo() {
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        HttpTools httptools = new HttpTools(getActivity());
        httptools.updateLogo(token, key, new JsonInfo());
    }

    public class JsonPerson extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(getActivity(), "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
            try {
                Log.i("zq", response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    JSONObject object = response.getJSONObject("data");
                    String name = object.getString("name");
                    String username = object.getString("username");
                    String logo = object.getString("logo");
                    String balance = object.getString("balance");
                    String score = object.getString("score");
                    tv_name.setText(name);
                    tv_shoujihao.setText(username);
//					tv_yue.setText(""+(int)(Double.parseDouble(balance)*10));
//					tv_jifen.setText(""+(int)(Double.parseDouble(score)*10));
                    tv_yue.setText(balance);
                    tv_jifen.setText(score);
                    Editor editor = sp.edit();
                    editor.putString("avatar", logo);
                    editor.commit();
                    ImageUtilsTouxiang.displayImage(getActivity(), sp.getString("avatar", ""), iv_touxiang, R.drawable.touxiang1);
                } else {
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private class JsonInfo extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                Log.i("zq", "info---" + response.toString());
                if (code == true) {
                    Personal();
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


}

